package com.zkh360.service.message.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import com.zkh360.service.message.constant.ErrorCode;
import com.zkh360.service.message.controller.base.BaseController;
import com.zkh360.service.message.exceptions.BusinessException;
import com.zkh360.service.message.model.BaseResponse;
import com.zkh360.service.message.model.SysAuthorityVO;
import com.zkh360.service.message.model.SysRoleVO;
import com.zkh360.service.message.model.SysRolesAuthorityVO;
import com.zkh360.service.message.model.SysUserVO;
import com.zkh360.service.message.service.AuthorityService;

import lombok.extern.slf4j.Slf4j;

@Controller
@Slf4j
public class AuthorityConrtroller extends BaseController {
	
	@Autowired
	private AuthorityService authorityService;
	
	/**
	 * 获取资源信息（主要是URL地址）
	 * 
	 * @return
	 */
	@GetMapping("/authorities")
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	public String getResources(Long userId, String userAccount, Model model) {
		log.info("获取资源信息");
		SysUserVO sysUsers = new SysUserVO();
		sysUsers.setUser_account(userAccount);
		sysUsers.setUser_id(userId);
		List<SysAuthorityVO> sysAuthorityList = authorityService.getAuthoritysByUser(sysUsers);
		// 前端返回
		model.addAttribute("authorities", sysAuthorityList);
		return "authorities";
	}
	
	/**
	 * 获取资源信息
	 * 主要是点击修改按钮获取详情
	 * 
	 * @throws IOException IO异常
	 */
	@GetMapping("/authority")
	public void getAuthority(Integer authorityId, HttpServletResponse response) throws IOException {
		log.info("获取资源信息详情");
		SysAuthorityVO sysAuthorityVo = new SysAuthorityVO();
		sysAuthorityVo.setAuthority_id(authorityId);
		List<SysAuthorityVO> sysAuthorityVoList = authorityService.getAuthorities(sysAuthorityVo);
		BaseResponse<SysAuthorityVO> result = BaseResponse.sucess(ErrorCode.CODE_SUCESS, "success", null);

		if (sysAuthorityVoList.size() == 0) {
			result = BaseResponse.fail(ErrorCode.CODE_FAILURE, "查询不到该权限信息！", null);
		} else if (sysAuthorityVoList.size() == 1) {
			result.setResult(sysAuthorityVoList.get(0));
		} else {
			result = BaseResponse.fail(ErrorCode.CODE_FAILURE, "查询到多个权限信息！", null);
		}

		writeJSON(response, result);
	}
	
	/**
	 * 新增资源信息（主要是URL地址）
	 * 
	 * @throws IOException
	 *             读写异常
	 */
	@PostMapping("/authority/add")
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	public void addAuthority(@RequestBody SysAuthorityVO sysAuthorityVo, HttpServletResponse response)
			throws IOException {
		log.info("添加权限信息");
		// 前端返回
		BaseResponse<String> result = BaseResponse.sucess(ErrorCode.CODE_SUCESS, "success", "添加成功");
		try {
			authorityService.addAuthority(sysAuthorityVo);
		} catch (BusinessException e) {
			log.error("添加权限信息异常", e.getErrorMsg());
			result = BaseResponse.fail(e.getErrorCode(), "fail", e.getErrorMsg());
		}

		writeJSON(response, result);
	}
	
	
	/**
	 * 删除权限信息
	 * 
	 * @throws IOException IO异常
	 */
	@GetMapping("/authority/delete")
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	public void deleteAuthority(Integer authorityId, HttpServletResponse response) throws IOException {
		log.info("删除权限信息详情");
		BaseResponse<String> result = BaseResponse.sucess(ErrorCode.CODE_SUCESS, "success", "删除成功");

		try {
			authorityService.deleteAuthority(authorityId);
		} catch (BusinessException e) {
			log.error("删除权限信息异常", e.getErrorMsg());
			result = BaseResponse.fail(e.getErrorCode(), "fail", e.getErrorMsg());
		}

		writeJSON(response, result);
	}
	
	/**
	 * 修改资源信息（主要是URL地址）
	 * 
	 * @throws IOException
	 *             读写异常
	 */
	@PostMapping("/authority/edit")
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	public void editAuthority(@RequestBody SysAuthorityVO sysAuthorityVo, HttpServletResponse response)
			throws IOException {
		log.info("修改资源信息");
		// 前端返回
		BaseResponse<String> result = BaseResponse.sucess(ErrorCode.CODE_SUCESS, "success", "添加成功");
		try {
			authorityService.editAuthority(sysAuthorityVo);
		} catch (BusinessException e) {
			log.error("添加资源信息异常", e.getErrorMsg());
			result = BaseResponse.fail(e.getErrorCode(), "fail", e.getErrorMsg());
		}

		writeJSON(response, result);
	}
	
	/**
	 * 获取权限信息
	 * 主要是角色点击修改按钮获取权限信息
	 * 
	 * @throws IOException IO异常
	 */
	@GetMapping("/authority/role/list")
	public void getAuthorityByRole(Long roleId, HttpServletResponse response) throws IOException {
		log.info("获取权限信息详情");
		List<SysAuthorityVO> allSysAuthorityList = authorityService.getAuthorities(new SysAuthorityVO());
		
		SysRoleVO sysRoleVo = new SysRoleVO();
		sysRoleVo.setRole_id(roleId);
		List<SysAuthorityVO> sysAuthorityVoList = authorityService.getAuthoritysByRole(sysRoleVo);
		
		Map<Integer, String> authorityMap = new HashMap<>();
		sysAuthorityVoList.forEach(sysAuthorityVo -> {
			authorityMap.put(sysAuthorityVo.getAuthority_id(), "");
		});
		
		allSysAuthorityList.forEach(sysAuthorityVo -> {
			if(authorityMap.containsKey(sysAuthorityVo.getAuthority_id())) {
				sysAuthorityVo.setIfInuse(true);
			}
		});
		BaseResponse<List<SysAuthorityVO>> result = BaseResponse.sucess(ErrorCode.CODE_SUCESS, "success", allSysAuthorityList);
		writeJSON(response, result);
	}
	
	/**
	 * 修改资源权限信息
	 * 
	 * @throws IOException 读写异常
	 */
	@PostMapping("/authority/role/edit")
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	public void ediAuthorityByRole(@RequestBody List<SysRolesAuthorityVO> sysRolesAuthorityVoList, HttpServletResponse response)
			throws IOException {
		log.info("配置角色权限操作");
		// 前端返回
		BaseResponse<String> result = BaseResponse.sucess(ErrorCode.CODE_SUCESS, "success", "添加成功");
		try {
			authorityService.ediAuthorityByRole(sysRolesAuthorityVoList);
		} catch (BusinessException e) {
			log.error("配置角色权限操作异常", e.getErrorMsg());
			result = BaseResponse.fail(e.getErrorCode(), "fail", e.getErrorMsg());
		}

		writeJSON(response, result);
	}
	
}
